package com.defysoft.waukidsschool.scanmode;

import java.util.Calendar;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukidsschool.BaseActivity;
import com.defysoft.waukidsschool.R;
import com.defysoft.waukidsschool.Wake_Screen;
import com.defysoft.waukidsschool.main.Main_Intro;

public class Scanmode_SetTime extends BaseActivity {
	NumberPicker[] starttime = new NumberPicker[4];
	NumberPicker[] backtime = new NumberPicker[4];
	Calendar calendar;
	int nowhour = 0;
	int nowmin = 0;
	Toolbar toolbar;
	ImageView iv;
	Button button;
	EditText et;
	EditText et2;
	EditText check;
	int resultint = 0;
	AlertDialog alert;
	SharedPreferences settingtime;
	SharedPreferences.Editor editor;
	SharedPreferences restarttime;
	SharedPreferences.Editor reeditor;
	private SharedPreferences login_code;
	int settime[] = new int[4];
	final int SUCCESS = 10;
	final int FAIR = 9;
	final int SUBSUCCESS = 8;
	final int SUBFAIR = 7;
	private String sch_code = null;
	private String limit = null;
	private String time = null;
	TextView logout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_scanmode__set_time);
		Wake_Screen.acquireCpuWakeLock(this);
		try {
			resultint = getIntent().getIntExtra("AUTOSTART", 0);
		} catch (Exception e) {
			// TODO: handle exception
		}
		login_code = getSharedPreferences("login_code", MODE_PRIVATE);
		sch_code = login_code.getString("sch_code", null);
		setStartData();

	}

	@Override
	public void setStartData() {
		// TODO Auto-generated method stub
		super.setStartData();
		et = (EditText) findViewById(R.id.SCHOOL_SET_SCANTIME);
		et2 = (EditText) findViewById(R.id.SCHOOL_SET_RESTART);
		check = (EditText) findViewById(R.id.SCHOOL_SET_CHECKLIMIT);
		calendar = Calendar.getInstance();
		nowhour = calendar.get(Calendar.HOUR_OF_DAY);
		nowmin = calendar.get(Calendar.MINUTE);
		button = (Button) findViewById(R.id.RESET_BTN);
		settingtime = getSharedPreferences("settingtime", MODE_PRIVATE);
		restarttime = getSharedPreferences("restarttime", MODE_PRIVATE);
		editor = settingtime.edit();
		reeditor = restarttime.edit();
		logout=(TextView)findViewById(R.id.MAIN_TIME_LOGOUT);
		et2.setText(restarttime.getString("restart", "0"));
		iv = (ImageView) findViewById(R.id.SET_START);
		starttime[0] = (NumberPicker) findViewById(R.id.SET_TIME_STARTGO_HOUR);
		starttime[1] = (NumberPicker) findViewById(R.id.SET_TIME_STARTGO_MIN);
		starttime[2] = (NumberPicker) findViewById(R.id.SET_TIME_ENDGO_HOUR);
		starttime[3] = (NumberPicker) findViewById(R.id.SET_TIME_ENDGO_MIN);
		backtime[0] = (NumberPicker) findViewById(R.id.SET_TIME_STARTBACK_HOUR);
		backtime[1] = (NumberPicker) findViewById(R.id.SET_TIME_STARTBACK_MIN);
		backtime[2] = (NumberPicker) findViewById(R.id.SET_TIME_ENDBACK_HOUR);
		backtime[3] = (NumberPicker) findViewById(R.id.SET_TIME_ENDBACK_MIN);

		for (int i = 0; i < starttime.length; i += 2) {
			starttime[i].setMaxValue(23);
			starttime[i].setMinValue(0);

			starttime[i + 1].setMaxValue(59);
			starttime[1 + 1].setMinValue(0);

			backtime[i].setMaxValue(23);
			backtime[i].setMinValue(0);

			backtime[i + 1].setMaxValue(59);
			backtime[1 + 1].setMinValue(0);

		}
		try {
			if (!settingtime.getString("STARTGO", null).equals(null)
					&& !settingtime.getString("ENDGO", null).equals(null)
					&& !settingtime.getString("STARTBACK", null).equals(null)
					&& !settingtime.getString("ENDBACK", null).equals(null)) {
				settime[0] = Integer.parseInt(settingtime.getString("STARTGO",
						"0"));
				settime[1] = Integer.parseInt(settingtime.getString(
						"STARTBACK", "0"));
				settime[2] = Integer.parseInt(settingtime.getString("ENDGO",
						"0"));
				settime[3] = Integer.parseInt(settingtime.getString("ENDBACK",
						"0"));
				starttime[0].setValue(settime[0] / 100);
				starttime[1].setValue(settime[0] % 100);
				backtime[0].setValue(settime[2] / 100);
				backtime[1].setValue(settime[2] % 100);
				starttime[2].setValue(settime[1] / 100);
				starttime[3].setValue(settime[1] % 100);
				backtime[2].setValue(settime[3] / 100);
				backtime[3].setValue(settime[3] % 100);
			} else {
				for (int i = 0; i < starttime.length; i += 2) {
					starttime[i].setValue(nowhour);
					starttime[i + 1].setValue(nowmin);
					backtime[i].setValue(nowhour);
					backtime[i + 1].setValue(nowmin);
				}
			}
		} catch (Exception e) {
			for (int i = 0; i < starttime.length; i += 2) {
				starttime[i].setValue(nowhour);
				starttime[i + 1].setValue(nowmin);
				backtime[i].setValue(nowhour);
				backtime[i + 1].setValue(nowmin);
			}
		}

		toolbar = (Toolbar) findViewById(R.id.SET_TIME_TOOL);
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				AlertDialog.Builder builder = new AlertDialog.Builder(
						Scanmode_SetTime.this);
				builder.setMessage("저장된 출결상태를 모두 지우시겠습니까?")
						.setCancelable(false)
						.setPositiveButton("지우기",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										SharedPreferences log_data = getSharedPreferences(
												"log_data", MODE_PRIVATE);
										log_data.edit().clear().commit();
										Toast.makeText(Scanmode_SetTime.this,
												"모든기록이 지워졌습니다.",
												Toast.LENGTH_SHORT).show();
									}
								})
						.setNegativeButton("종료",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.cancel();
									}
								});
				alert = builder.create();
				alert.show();
			}
		});
		logout.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				AlertDialog.Builder builder = new AlertDialog.Builder(
						Scanmode_SetTime.this);
				builder.setMessage(
						"로그아웃 하겠습니까?")
						.setCancelable(false)
						.setPositiveButton("네",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										editor=login_code.edit();
										editor.putString("sch_code", null);
										editor.putString("sch_name", null);
										editor.commit();
										startActivity(new Intent(Scanmode_SetTime.this, Main_Intro.class).addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY));
										dialog.cancel();
										finish();
									}
								})
						.setNegativeButton("아니오",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.cancel();
									}
								});
				AlertDialog alert = builder.create();
				alert.show();
			}
		});
		iv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				settime[0] = (starttime[0].getValue() * 100)
						+ starttime[1].getValue();
				settime[1] = (starttime[2].getValue() * 100)
						+ starttime[3].getValue();
				settime[2] = (backtime[0].getValue() * 100)
						+ backtime[1].getValue();
				settime[3] = (backtime[2].getValue() * 100)
						+ backtime[3].getValue();
				if (settime[0] >= settime[1]) {
					Toast.makeText(Scanmode_SetTime.this,
							"등원시간의 시작시간이 종료시간보다 전 이어야 합니다.", Toast.LENGTH_SHORT)
							.show();
				} else if (settime[2] >= settime[3]) {
					Toast.makeText(Scanmode_SetTime.this,
							"하원시간의 시작시간이 종료시간보다 전 이어야 합니다.", Toast.LENGTH_SHORT)
							.show();
				} else if (settime[1] >= settime[2]) {
					Toast.makeText(Scanmode_SetTime.this,
							"등원종료시간이 하원시작시간보다 전 이어야 합니다.", Toast.LENGTH_SHORT)
							.show();
				} else if (Integer.parseInt(check.getText().toString()) <= 0) {
					Toast.makeText(Scanmode_SetTime.this,
							"귀가 체크횟수는 최소 1이상이어야 합니다.", Toast.LENGTH_SHORT)
							.show();
				} else if (Integer.parseInt(et2.getText().toString()) < Integer
						.parseInt(et.getText().toString()) + 5
						&& Integer.parseInt(et2.getText().toString()) != 0) {
					Toast.makeText(Scanmode_SetTime.this,
							"비콘스캔 주기가 다시켜지는시간보다 적어도 5초는 짧아야 합니다.",
							Toast.LENGTH_SHORT).show();
				} else {
					reeditor.putString("restart", et2.getText().toString())
							.commit();
					startThread(2);
				}
			}
		});

		if (resultint == 1) {
			reeditor.putString("restart", et2.getText().toString()).commit();
			startThread(2);
		}
		startThread(1);
	}

	@Override
	public void startThread(int choice) {
		// TODO Auto-generated method stub
		super.startThread(choice);
		final int cho = choice;
		firstThread = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				switch (cho) {
				case 1:
					mainThread();
					break;
				case 2:
					subThread();
					break;
				}
			}
		});
		firstThread.start();
		startDIal();
	}

	public void mainThread() {
		boolean checkt = true;
		while (checkt) {

			try {
				JSONObject jsonObject = new JSONObject(publicHttpCallback(
						HTTP_SETTIME, "code=" + sch_code));
				if (jsonObject.getBoolean("success")) {
					time = jsonObject.getString("time");
					limit = jsonObject.getString("limit");
					onNetworkCallback(SUCCESS, "");
					checkt = false;
				} else {
					onNetworkCallback(FAIR, "");
				}
			} catch (Exception e) {
				onNetworkCallback(FAIR, "");
			}
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void subThread() {
		boolean checkb = true;
		while (checkb) {
			try {
				JSONObject jsonObject = new JSONObject(publicHttpCallback(
						HTTP_GETTIME, "code=" + sch_code + "&time="
								+ et.getText().toString() + "&limit="
								+ check.getText().toString()));
				if (jsonObject.getBoolean("success")) {
					onNetworkCallback(SUBSUCCESS, "");
					checkb = false;
				} else {
					onNetworkCallback(SUBFAIR, "");
				}
			} catch (Exception e) {
				onNetworkCallback(SUBFAIR, "");
			}
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	@Override
	protected void handlingMessage(Message _message) {
		// TODO Auto-generated method stub
		super.handlingMessage(_message);
		switch (_message.what) {
		case SUCCESS:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			et.setText(time);
			check.setText(limit);
			endDIal();
			break;
		case FAIR:

			Toast.makeText(this, "네트워크오류로 정보갱신실패 다시 정보를 얻어옵니다.",
					Toast.LENGTH_SHORT).show();
			break;
		case SUBSUCCESS:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			startScanActivity();
			break;
		case SUBFAIR:
			Toast.makeText(this, "네트워크오류로 정보갱신실패 다시 정보를 얻어옵니다.",
					Toast.LENGTH_SHORT).show();
			break;

		}
	}

	void startScanActivity() {
		editor.putString("STARTGO", settime[0] + "");
		editor.putString("STARTBACK", settime[1] + "");
		editor.putString("ENDGO", settime[2] + "");
		editor.putString("ENDBACK", settime[3] + "");
		editor.commit();
		if (Integer.parseInt(restarttime.getString("restart", "0")) == 0) {
			Calendar cal = Calendar.getInstance();
			int time = ((starttime[0].getValue()) - (cal
					.get(Calendar.HOUR_OF_DAY)));
			int minute = ((starttime[1].getValue()) - (cal.get(Calendar.MINUTE)));
			cal.add(Calendar.DATE, 1);
			cal.add(Calendar.HOUR_OF_DAY, time);
			cal.add(Calendar.MINUTE, minute);
			// cal.add(Calendar.SECOND, 360);
			cal.set(Calendar.SECOND, 0);

			// Create a new PendingIntent and add it to the AlarmManager
			Intent intent = new Intent(Scanmode_SetTime.this, Main_Intro.class)
					.putExtra("AUTOSTART", 1);
			PendingIntent pendingIntent = PendingIntent.getActivity(
					Scanmode_SetTime.this, 12345, intent,
					PendingIntent.FLAG_CANCEL_CURRENT);
			AlarmManager am = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
			am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
					pendingIntent);

			startActivity(new Intent(Scanmode_SetTime.this,
					Scanmode_StartScan.class)
					.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
					.putExtra("second", et.getText().toString())
					.putExtra("checklimit", check.getText().toString()));
		} else {
			Calendar cal = Calendar.getInstance();
			int time = ((starttime[0].getValue()) - (cal
					.get(Calendar.HOUR_OF_DAY)));
			int minute = ((starttime[1].getValue()) - (cal.get(Calendar.MINUTE)));
			// cal.add(Calendar.DATE, 1);
			// cal.add(Calendar.HOUR_OF_DAY, time);
			// cal.add(Calendar.MINUTE, minute);
			cal.add(Calendar.SECOND,
					Integer.parseInt(restarttime.getString("restart", "60")));
			// cal.set(Calendar.SECOND, 0);

			// Create a new PendingIntent and add it to the AlarmManager
			Intent intent = new Intent(Scanmode_SetTime.this, Main_Intro.class)
					.putExtra("AUTOSTART", 1);
			PendingIntent pendingIntent = PendingIntent.getActivity(
					Scanmode_SetTime.this, 12345, intent,
					PendingIntent.FLAG_CANCEL_CURRENT);
			AlarmManager am = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
			am.cancel(pendingIntent);
			am = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
			am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
					pendingIntent);

			startActivity(new Intent(Scanmode_SetTime.this,
					Scanmode_StartScan.class)
					.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
					.putExtra("second", et.getText().toString())
					.putExtra("checklimit", check.getText().toString()));
		}
	}
}
